<template>
  <div class="health-box">
    <div class="title-box">
      <div class="dateTime">
        <div class="date">
          <a-date-picker
            :open="dateTimeShow == true ? true : false"
            v-model:value="dateValue"
            :format="dateFormat"
            @change="handleChange"
            popupClassName="datePickerTwo"
            :showToday="true"
            @panelChange="handlePanelChange"
          >
            <!-- :disabled-date="disabledDate" -->
            <template #dateRender="{ current }">
              <div class="foodRecordDateWrap">
                <p>
                  {{ current.date() }}
                </p>
                <p
                  :class="
                    dateList[current.date() - 1] && dateList[current.date() - 1].dietInfoNum
                      ? 'on'
                      : ''
                  "
                >
                  <span
                    v-if="dateList[current.date() - 1] && dateList[current.date() - 1].dietInfoNum"
                    class="food"
                  />
                  <!-- <span
                    class="suggestion"
                    v-if="
                      dateList[current.date() - 1] && dateList[current.date() - 1].dietAdviceNum
                    "
                  /> -->
                </p>
              </div>
            </template>
          </a-date-picker>
        </div>
        <div class="list">
          <div class="item">
            <img src="@/assets/health/foodDuiTwo.png" alt="" />
            <p>饮食记录</p>
          </div>
          <!-- <div class="item">
            <img src="@/assets/health/foodDui.png" alt="" />
            <p>医护建议</p>
          </div> -->
        </div>
      </div>
      <div class="foodDrink">
        <div class="title">
          <span>当日饮食记录</span>
          <span
            >（实际摄入<i>{{ foodIntake.energy ? foodIntake.energy : 0 }}</i
            >千卡</span
          >
          <span v-if="foodIntake.adviceEnergy"
            >/推荐{{ foodIntake.adviceEnergy ? foodIntake.adviceEnergy : 0 }}千卡</span
          >）
        </div>
        <div class="foodWrap">
          <div class="left">
            <p
              v-for="(item, index) in foodList"
              :key="index"
              :class="foodActive == index ? 'on' : ''"
              @click="foodCli(index)"
            >
              {{ item.name }}
            </p>
          </div>
          <div class="listScroll" ref="listScrollRef">
            <div class="listRight">
              <div
                class="item"
                :ref="(el) => setItemRef(el, index)"
                v-for="(item, index) in foodRecordList"
                :key="index"
              >
                <div class="top">
                  <p>
                    <span>{{ item.name }}记录</span>
                    <RightOutlined />
                  </p>
                  <p>
                    <span class="on" v-if="item.title">{{ item.energy }}：</span>
                    <span>{{ item.title || '未记录' }}</span>
                  </p>
                </div>
                <!-- <div class="top photo">
                  <p :class="item.activePic ? 'on' : ''" @click="recodeFun(item, '1')">
                    <span>{{ item.name }}照片</span>
                    <RightOutlined />
                  </p>
                  <p v-if="item.activePic">
                    <a-upload
                      v-model:file-list="item.picList"
                      list-type="picture-card"
                      accept=".jpg,.jpeg,.png"
                      @preview="handlePreviewOne"
                      :customRequest="(options) => customRequest(options, item)"
                      class="imgList"
                    >
                      <div v-if="item.picList.length < 9">
                        <plus-outlined />
                      </div>
                    </a-upload>
                    <a-modal
                      v-model:open="previewVisibleOne"
                      :title="previewTitle"
                      :footer="null"
                      @cancel="handleCancel"
                    >
                      <img alt="example" style="width: 100%" :src="previewImage" />
                    </a-modal>
                  </p>
                </div> -->
                <!-- <div class="top suggestion">
                  <p :class="item.activeCon ? 'on' : ''" @click="recodeFun(item, '2')">
                    <span>医护建议</span>
                    <RightOutlined />
                  </p>
                  <p v-if="item.activeCon">
                    <textarea
                      placeholder="请输入医护建议(最多输入500字)"
                      maxlength="500"
                      class="textarea"
                      rows="3"
                      v-model="item.content"
                    />
                  </p>
                </div> -->
              </div>
            </div>
          </div>
        </div>
        <!-- <div class="foodBtn">
          <p @click="save">保存</p>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import {
  foodDateList,
  foodInfoList,
  infoUpload,
  infotGetEnergy,
  infotSave
} from '@/api/patientMana/index.ts'
import { RightOutlined, PlusOutlined } from '@ant-design/icons-vue'
import dayjs, { Dayjs } from 'dayjs'
import { message } from 'ant-design-vue'

const empiValue = ref('')
const dateTimeShow = ref(true)
const dateList = ref([])
const foodList = ref([
  { name: '早餐' },
  { name: '早加餐' },
  { name: '午餐' },
  { name: '午加餐' },
  { name: '晚餐' },
  { name: '晚加餐' }
])
const foodActive = ref(0)
const listScrollRef = ref()
// const listref0 = ref(null)
// const listref1 = ref(null)
// const listref2 = ref(null)
// const listref3 = ref(null)
// const listref4 = ref(null)
// const listref5 = ref(null)

const initialFoodRecordList = [
  {
    name: '早餐',
    type: 'BREAKFAST',
    activePic: false,
    activeCon: false,
    energy: '',
    title: '',
    content: '',
    picList: []
  },
  {
    name: '早加餐',
    type: 'BREAKFAST_PLUS',
    activePic: false,
    activeCon: false,
    energy: '',
    title: '',
    content: '',
    picList: []
  },
  {
    name: '午餐',
    type: 'LUNCH',
    activePic: false,
    activeCon: false,
    energy: '',
    title: '',
    content: '',
    picList: []
  },
  {
    name: '午加餐',
    type: 'LUNCH_PLUS',
    activePic: false,
    activeCon: false,
    energy: '',
    title: '',
    content: '',
    picList: []
  },
  {
    name: '晚餐',
    type: 'DINNER',
    activePic: false,
    activeCon: false,
    energy: '',
    title: '',
    content: '',
    picList: []
  },
  {
    name: '晚加餐',
    type: 'DINNER_PLUS',
    activePic: false,
    activeCon: false,
    energy: '',
    title: '',
    content: '',
    picList: []
  }
]

const foodRecordList = ref([...initialFoodRecordList])

// 日期
const dateFormat = ref('YYYY/MM/DD')
const dateValue = ref<any>() //当前的年月日
const dateByMonth = ref() // 当前日历年月
const dateListYear = ref('')
const dateListMon = ref('')
const dateListDay = ref('') //当前高亮的日
// 上传图片
// const previewVisible = ref(false)
const previewVisibleOne = ref(false)

const previewImage = ref('')
const previewTitle = ref('')
const foodRecode = ref({
  BREAKFAST: {
    hepDoctorDietAdvice: {
      picList: []
    }
  }
})

const fileList = ref([])

const foodIntake = ref({})

const refsMap = ref({})
const setItemRef = (el, index) => {
  if (el) {
    refsMap.value[`listref${index}`] = el
  }
}

// )
const init = async (id, isShow, date?: any) => {
  dateTimeShow.value = isShow

  const currentDate = date || dayjs(new Date()).format('YYYY-MM-DD')
  dateValue.value = dayjs(currentDate)
  dateByMonth.value = dayjs(currentDate).format('YYYY-MM')

  empiValue.value = id
  foodDateListFun()
  foodInfoListFun()
  foodInfoGetEnergyFun()
}
// 获取日期
const foodDateListFun = () => {
  const param = {
    empi: empiValue.value,
    // empi: '93c86056e0d2d23385fcde7ed96da25f',
    month: dayjs(dateByMonth.value).format('YYYY-MM')
  }
  foodDateList(param).then((res) => {
    dateList.value = res.data
  })
}
const foodInfoListFun = () => {
  foodRecordList.value = JSON.parse(JSON.stringify(initialFoodRecordList))
  const param = {
    empi: empiValue.value,
    // empi: '93c86056e0d2d23385fcde7ed96da25f',
    dietDate: dayjs(dateValue.value).format('YYYY-MM-DD')
    // dietDate: '2024-11-11'
  }
  foodInfoList(param).then((res) => {
    foodRecode.value = res.data
    // 早餐
    if (foodRecode.value) {
      const food_keys = Object.keys(foodRecode.value)

      food_keys.forEach((vo) => {
        foodRecordList.value.forEach((v, index) => {
          if (v.type == vo) {
            v.activePic = false
            v.activeCon = false
            v.energy = foodRecode.value[vo].allEnergy + '千卡' || ''

            const dietData = foodRecode.value[vo].hepDietInfo.map((co) => {
              return co.dietName + co.amount + '克，' + co.energy + '千卡'
            })
            v.title = dietData.join('；')

            const picListData = foodRecode.value[vo].hepDoctorDietAdvice?.picList

            if (picListData && picListData.length) {
              v.activePic = true
              const currentPicData = picListData.map((co) => {
                return {
                  ...co,
                  url: co.picUrl,
                  fileId: co.picId
                }
              })
              v.picList = JSON.parse(JSON.stringify(currentPicData))
            } else {
              v.picList = []
            }

            const contentData = foodRecode.value[vo].hepDoctorDietAdvice?.content
            if (contentData) {
              v.activeCon = true
              v.content = contentData
            }
          }
        })
      })

      foodActive.value = 0
      nextTick(() => {
        listScrollRef.value.scrollIntoView({ behavior: 'smooth' })
      })
    }
  })
}
const foodInfoGetEnergyFun = () => {
  const param = {
    empi: empiValue.value,
    // empi: '93c86056e0d2d23385fcde7ed96da25f',
    dietDate: dayjs(dateValue.value).format('YYYY-MM-DD')
    // dietDate: '2024-11-11'
  }
  infotGetEnergy(param).then((res) => {
    foodIntake.value = res.data
  })
}
const handleChange = (val) => {
  dateValue.value = val
  dateByMonth.value = dayjs(val).format('YYYY-MM')
  foodInfoListFun()
  foodInfoGetEnergyFun()
  foodDateListFun()
}

const handlePanelChange = (value) => {
  dateByMonth.value = dayjs(value).format('YYYY-MM')

  foodDateListFun()
}

const foodCli = (index) => {
  foodActive.value = index
  refsMap.value['listref' + index].scrollIntoView({ behavior: 'smooth' })
}
// 上传图片
const recodeFun = (data, num) => {
  if (num == 1) {
    data.activePic = !data.activePic
  } else {
    data.activeCon = !data.activeCon
  }
}
const customRequest = (options, data) => {
  const isLt2M = options.file.size / 1024 / 1024 < 10
  if (!isLt2M) {
    message.error('上传图片大小不能超过 10MB!')
    data.picList.splice(-1, 1)
    return false
  }
  const formData = new FormData()
  formData.append('imgFile', options.file) // 这里的 'file' 是后端接收文件的字段名
  infoUpload(formData).then((res) => {
    data.picList.push(res.data)
    data.picList.splice(-2, 1)
  })
  return true
}

const getBase64 = (file: File) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}
const handleCancel = () => {
  //   previewVisible.value = false
  previewVisibleOne.value = false
  previewTitle.value = ''
}
// const handlePreview = async (file) => {
//   if (!file.url && !file.preview) {
//     file.preview = (await getBase64(file.originFileObj)) as string
//   }
//   previewImage.value = file.url || file.preview
//   previewVisible.value = true
//   previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
// }
const handlePreviewOne = async (file) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string
  }
  previewImage.value = file.url || file.preview
  previewVisibleOne.value = true
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}

const save = () => {
  let dataList = []

  dataList = foodRecordList.value.map((item) => {
    const picList = item.picList.map((vo) => {
      return {
        picId: vo.fileId ? vo.fileId : '',
        picUrl: vo.relativePath
      }
    })

    return {
      empi: empiValue.value,
      dietDate: dateListYear.value + '-' + dateListMon.value + '-' + dateListDay.value,
      dietType: item.name,
      content: item.content,
      picList: picList || []
    }
  })

  infotSave(dataList).then((res) => {
    if (res.code == 0) {
      message.success(res.data, 3, () => {
        foodDateListFun()
      })
      // setTimeout(() => {
      //   foodDateListFun()
      // }, 2000)
    }
  })
}

defineExpose({
  init
})
</script>

<style lang="less" scoped>
.title-box {
  position: relative;
  height: calc(100vh - 225px);
  overflow: hidden;

  .dateTime {
    position: absolute;
    top: 0;
    left: 0;
    width: 280px;

    .date {
      margin-top: -38px;
      opacity: 0.0001;
    }

    .list {
      margin-top: 340px;

      .item {
        margin-top: 10px;

        img {
          display: inline-block;
          width: 24px;
          height: 24px;
          vertical-align: middle;
        }

        p {
          display: inline-block;
          margin: 0 0 0 5px;
          vertical-align: middle;
        }
      }
    }
  }

  .foodDrink {
    height: 100%;
    padding-left: 316px;

    .title {
      span {
        &:nth-child(1) {
          font-weight: 700;
          color: #000;
        }

        i {
          font-style: normal;
          color: #f53f3f;
        }
      }
    }

    .foodWrap {
      height: calc(100% - 84px);
      margin-top: 20px;
      overflow: hidden;

      .left {
        display: inline-block;
        width: 60px;
        vertical-align: top;

        p {
          padding: 5px 0;
          margin-bottom: 10px;
          text-align: center;
          border: 1px solid #e5e6eb;
          border-radius: 4px;

          &:hover {
            color: #1677ff;
            cursor: pointer;
            opacity: 0.8;
          }

          &.on {
            color: #fff;
            background: #1677ff;
          }
        }
      }

      .listScroll {
        display: inline-block;
        width: calc(100% - 76px);
        height: 100%;
        margin-left: 16px;
        overflow: auto;
        vertical-align: top;

        .listRight {
          .item {
            padding-bottom: 10px;
            color: #666;
            border-bottom: 1px solid #e5e6eb;

            .top {
              margin-top: 5px;

              p {
                display: inline-block;
                margin: 0;
                vertical-align: top;

                &:nth-child(1) {
                  width: 90px;
                  margin-right: 10px;

                  span {
                    &:nth-child(1) {
                      margin-right: 5px;
                    }
                  }

                  .anticon {
                    width: 12px;
                    height: 12px;
                    margin-top: 0;
                    color: #fff;
                    transition: all 0.2s ease-in;
                    transform: rotate(90deg);
                  }
                }

                &:nth-child(2) {
                  position: relative;
                  width: calc(100% - 110px);

                  span {
                    &.on {
                      font-weight: 700;
                    }
                  }
                }
              }

              &.photo {
                p {
                  &:nth-child(1) {
                    width: 90px;
                    margin-right: 10px;

                    span {
                      &:nth-child(1) {
                        margin-right: 5px;
                      }
                    }

                    .anticon {
                      width: 12px;
                      height: 12px;
                      margin-top: 0;
                      color: #666;
                      transition: all 0.2s ease-in;
                      transform: rotate(90deg);
                    }

                    &.on {
                      .anticon {
                        transform: rotate(-90deg);
                      }
                    }

                    &:hover {
                      cursor: pointer;
                      opacity: 0.8;
                    }
                  }

                  &:nth-child(2) {
                    position: relative;
                    width: calc(100% - 100px);

                    span {
                      &:nth-child(1) {
                        color: #165dff;
                      }
                    }
                  }

                  ::v-deep(.imgList) {
                    .ant-upload-list {
                      .ant-upload-list-item-container {
                        width: 70px;
                        height: 70px;
                      }

                      .ant-upload-select-picture-card {
                        width: 70px;
                        height: 70px;
                      }
                    }
                  }
                }
              }

              &.suggestion {
                p {
                  &:nth-child(1) {
                    width: 80px;
                    margin-right: 10px;

                    span {
                      &:nth-child(1) {
                        margin-right: 5px;
                      }
                    }

                    .anticon {
                      width: 12px;
                      height: 12px;
                      margin-top: 0;
                      color: #666;
                      transition: all 0.2s ease-in;
                      transform: rotate(90deg);
                    }

                    &.on {
                      .anticon {
                        transform: rotate(-90deg);
                      }
                    }

                    &:hover {
                      cursor: pointer;
                      opacity: 0.8;
                    }
                  }

                  .textarea {
                    display: block;
                    width: 100%;
                    padding: 5px 10px;
                    appearance: none;
                    resize: none; /* 禁止拉伸 */
                    border: none;
                    border: 1px solid #d7d7d7; /* 带点绿 */
                    border-radius: 4px;
                    outline: none; /* 边线不显示 */
                    &::placeholder {
                      font-size: 12px;
                      font-weight: normal;
                      color: #ccc;
                    }
                  }
                }
              }
            }

            &:nth-child(1) {
              .top {
                margin-top: 0;
              }
            }
          }
        }
      }
    }

    .foodBtn {
      position: relative;

      p {
        position: absolute;
        top: 10px;
        right: 0;
        display: block;
        padding: 4px 15px;
        margin: 0;
        color: #fff;
        background: #1677ff;
        border-radius: 4px;

        &:hover {
          cursor: pointer;
          opacity: 0.8;
        }
      }
    }
  }
}
</style>
<style>
.ant-picker-dropdown.datePickerTwo {
  z-index: 10;
  border: 1px solid #e5e6eb;
}

.ant-picker-dropdown.datePickerTwo .ant-picker-panel-container {
  box-shadow: none;
}

.ant-picker-dropdown.datePickerTwo .foodRecordDateWrap {
  position: relative;
  border: 1px solid #fff;
  border-radius: 4px;
}

.ant-picker-dropdown.datePickerTwo
  .ant-picker-cell-in-view.ant-picker-cell-in-view
  .foodRecordDateWrap {
  color: #222;
}

.ant-picker-dropdown.datePickerTwo
  .ant-picker-cell-in-view.ant-picker-cell-today
  .foodRecordDateWrap {
  border: 1px solid #1890ff;
  border-radius: 0;
}

.ant-picker-dropdown.datePickerTwo
  .ant-picker-cell-in-view.ant-picker-cell-selected
  .foodRecordDateWrap {
  color: #fff;
  background: #1677ff;
  border: 1px solid #1890ff;
  border-radius: 0;
}

.ant-picker-dropdown.datePickerTwo .foodRecordDateWrap p {
  margin: 0;
}

.ant-picker-dropdown.datePickerTwo .foodRecordDateWrap p:nth-child(2) {
  position: absolute;
  bottom: -14px;
  left: 50%;
  transform: translateX(-50%);
}

.ant-picker-dropdown.datePickerTwo
  .ant-picker-cell.ant-picker-cell-disabled
  .foodRecordDateWrap
  .health-dates {
  color: rgba(0, 0, 0, 25%);
  background: none;
}

.ant-picker-dropdown.datePickerTwo
  .ant-picker-cell-in-view
  .foodRecordDateWrap
  p:nth-child(2)
  span {
  display: none;
}

.ant-picker-dropdown.datePickerTwo
  .ant-picker-cell-in-view.ant-picker-cell-in-view
  .foodRecordDateWrap
  p:nth-child(2)
  .food {
  display: inline-block;
  width: 4px;
  height: 4px;
  vertical-align: middle;
  background: #4c83ff;
  border-radius: 4px;
}

.ant-picker-dropdown.datePickerTwo
  .ant-picker-cell-in-view.ant-picker-cell-in-view
  .foodRecordDateWrap
  p:nth-child(2)
  .suggestion {
  display: inline-block;
  width: 4px;
  height: 4px;
  vertical-align: middle;
  background: #70b603;
  border-radius: 4px;
}

.ant-picker-dropdown.datePickerTwo
  .ant-picker-cell-in-view.ant-picker-cell-in-view
  .foodRecordDateWrap
  p:nth-child(2).on
  .suggestion {
  margin-left: 5px;
}

.css-dev-only-do-not-override-obgold.ant-picker-dropdown.datePickerTwo {
  z-index: 1;
}
</style>
